const express = require('express');
const router = express.Router();
const User = require('../models/User');
const auth = require('../middleware/auth');
const Challenge = require('../models/Challenge');
const Resource = require('../models/Resource');

// 获取当前用户信息 - 放在最前面
router.get('/me', auth, async (req, res) => {
  try {
    const user = await User.findById(req.userId).select('-password');
    if (!user) {
      return res.status(404).json({ message: '用户不存在' });
    }
    res.json(user);
  } catch (error) {
    console.error('获取用户信息失败:', error);
    res.status(500).json({ message: '获取用户信息失败' });
  }
});

// 获取用户进行中的挑战 - 也应该放在参数路由前面
router.get('/active-challenges', auth, async (req, res) => {
  try {
    const user = await User.findById(req.user.id)
      .populate('activeChallenges.challengeId');
    
    const activeChallenges = user.activeChallenges.map(ac => {
      const challenge = ac.challengeId;
      const startDate = new Date(ac.startDate);
      const endDate = new Date(startDate);
      endDate.setDate(endDate.getDate() + parseInt(challenge.duration));
      
      const now = new Date();
      const remainingDays = Math.ceil((endDate - now) / (1000 * 60 * 60 * 24));
      
      return {
        ...challenge.toObject(),
        progress: ac.progress,
        remainingDays: Math.max(0, remainingDays),
        completedTasks: ac.completedTasks
      };
    });
    
    res.json(activeChallenges);
  } catch (error) {
    res.status(500).json({ message: '获取进行中的挑战失败' });
  }
});

// 获取用户信息
router.get('/:id', auth, async (req, res) => {
  try {
    const user = await User.findById(req.params.id).select('-password');
    if (!user) {
      return res.status(404).json({ message: '用户不存在' });
    }
    res.json(user);
  } catch (error) {
    res.status(500).json({ message: error.message });
  }
});

// 更新用户信息
router.patch('/:id', auth, async (req, res) => {
  try {
    const updates = req.body;
    const allowedUpdates = ['username', 'bio', 'preferences'];
    const updateData = {};

    Object.keys(updates).forEach(key => {
      if (allowedUpdates.includes(key)) {
        updateData[key] = updates[key];
      }
    });

    const user = await User.findByIdAndUpdate(
      req.params.id,
      { $set: updateData },
      { new: true }
    ).select('-password');

    if (!user) {
      return res.status(404).json({ message: '用户不存在' });
    }

    res.json(user);
  } catch (error) {
    res.status(500).json({ message: error.message });
  }
});

// 获取用户统计信息
router.get('/:id/stats', auth, async (req, res) => {
  try {
    const user = await User.findById(req.params.id);
    if (!user) {
      return res.status(404).json({ message: '用户不存在' });
    }

    // 计算统计数据
    const stats = {
      totalPoints: user.points || 0,
      completedChallenges: user.completedChallenges?.length || 0,
      activeChallenges: user.activeChallenges?.length || 0,
      carbonSaved: user.carbonSaved || 0,
      rank: 0, // 可以根据需要计算排名
      achievements: user.achievements || []
    };

    res.json(stats);
  } catch (error) {
    console.error('获取用户统计失败:', error);
    res.status(500).json({ message: '获取用户统计失败' });
  }
});

// 获取用户成就
router.get('/:id/achievements', auth, async (req, res) => {
  try {
    const user = await User.findById(req.params.id)
      .select('achievements badges')
      .lean();

    if (!user) {
      return res.status(404).json({ message: '用户不存在' });
    }

    res.json({
      achievements: user.achievements || [],
      badges: user.badges || []
    });
  } catch (error) {
    res.status(500).json({ message: '获取成就失败' });
  }
});

module.exports = router; 